之前在添加資料時,都是手動去資料庫添加,這樣很不合理,也沒有效率
如果只是為了方便,當然可以使用以下的方法
def create(request):
for i in range(5):
student = Student()
student.name = '王'+str(i)
student.age = i
student.save()
return HttpResponse('create_suc')
但今天資料在excel裡面,該怎麼辦呢
在有外鍵的情況下,不能直接給值,還是要透過外鍵物件
一班來說openpyxl應改可以用相對路徑,但不知道為什麼在django下只能用絕對路徑
def create(request):
import openpyxl
wb = openpyxl.load_workbook('D:/create.xlsx')
wb.active = 0
ws = wb.active
num = 1
for row in ws:
if num == 1:
num += 1
continue
name = ws['A' + str(num)].value
age = ws['B' + str(num)].value
classroom = ws['C' + str(num)].value
student = Student()
student.name = name
student.age = age
student.classroom = ClassRoom.objects.filter(name=classroom).first()
student.save()
num += 1
return HttpResponse('create_suc')
如果有註冊頁面,也可以嘗試用selenium(後端一定要會selenium吧)
這邊就不再放註冊該怎麼做了,只看selenium程式碼
chromedriver上網查符合自己版本的,下載放到同一層
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import openpyxl
options = Options()
options.add_argument("--disable-notifications")
# 啟動 chrome driver
driver = webdriver.Chrome('chromedriver', options=options)
# 指定開啟網址
driver.get("http://127.0.0.1:8000/app/register/")
wb = openpyxl.load_workbook('D:/create.xlsx')
wb.active = 0
ws = wb.active
num = 1
for row in ws:
if num == 1:
num += 1
continue
name = ws['A' + str(num)].value
age = ws['B' + str(num)].value
classroom = ws['C' + str(num)].value
driver.find_element_by_name('name').send_keys(name)
driver.find_element_by_name('age').send_keys(age)
driver.find_element_by_name('classroom').send_keys(classroom)
driver.find_element_by_tag_name("button").click()
time.sleep(2)
我的註冊完成後有自動導向到原本頁面,所以可以一直跑